package com.miya.handler;

import cn.hutool.core.collection.CollUtil;
import com.miya.enums.ResponseEnum;
import com.miya.exception.BusinessException;

import java.util.Collection;
import java.util.Objects;

/**
 * 断言
 *
 * @author Caixiaowei
 * @date 2022/02/23
 */
public final class Assert {

	public static void isNull(Object object, String message) throws BusinessException {
		if (Objects.nonNull(object)) {
			throw new BusinessException(message);
		}
	}

	public static void nonNull(Object object, ResponseEnum code) {
		nonNull(object, code.getDesc());
	}

	public static void nonNull(Object object, String message) throws BusinessException {
		if (object == null) {
			throw new BusinessException(message);
		}
	}

	public static <T extends Collection> T requireNonEmpty(T coll, ResponseEnum message) throws BusinessException {
		return requireNonEmpty(coll, message.getDesc());
	}

	public static <T extends Collection> T requireNonEmpty(T coll, String message) throws BusinessException {
		if (CollUtil.isEmpty(coll)) {
			throw new BusinessException(message);
		} else {
			return coll;
		}
	}

	public static <T> T requireNonNull(T object, ResponseEnum message) throws BusinessException {
		return requireNonNull(object, message.getDesc());
	}

	public static <T> T requireNonNull(T object, String message) throws BusinessException {
		if (object == null) {
			throw new BusinessException(message);
		} else {
			return object;
		}
	}

	public static void state(boolean expression, String message) throws BusinessException {
		if (!expression) {
			throw new BusinessException(message);
		}
	}

	public static void state(boolean expression, ResponseEnum code) {
		state(expression, code.getDesc());
	}

	private Assert() {
		throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
	}
}
